package controllers

import (
	"bytes"
	"encoding/xml"
	"fmt"
	"github.com/revel/revel"
	"io/ioutil"
	"net/http"
	"strconv"
	"wuhuaguo.com/whg01/app/models"
	"wuhuaguo.com/whg01/app/models/message"
)

type WxApp struct {
	*revel.Controller
}

func (c WxApp) Wx(signature string,
	timestamp string, nonce string,
	echostr string) revel.Result {
	revel.INFO.Println(signature, timestamp, nonce, echostr)
	// token := "1987526ab"
	return c.RenderText(echostr)
}

func (c WxApp) WxP() revel.Result {
	body, err := ioutil.ReadAll(c.Request.Body)
	if err != nil {
		panic(err)
		return c.RenderText("error")
	}

	str := string(body)
	revel.INFO.Println(str)

	rm := message.HandleMsg(str)
	if rm != nil {
		var b bytes.Buffer
		enc := xml.NewEncoder(&b)
		enc.Indent("  ", "    ")
		if err := enc.Encode(rm); err != nil {
			revel.ERROR.Println("error: %v\n", err)
		}
		rsmsg := b.String()
		revel.INFO.Println(rsmsg)
		return c.RenderText(rsmsg)
	} else {
		return c.RenderText("")
	}

}

func (c WxApp) Login(code string, state string) revel.Result {
	revel.INFO.Println("code %s state %s", code, state)
	if code == "" {
		return c.RenderText("login fail %q", state)
	} else {
		//获取到了用户id
		resp, err := http.Get(fmt.Sprintf("https://api.weixin.qq.com/sns/oauth2/access_token?appid=wx05054be971d87487&secret=4c7cd224df5c0102c19301903521dcc6&code=%s&grant_type=authorization_code", code))
		if err != nil {
			return c.RenderText(err.Error())
		} else {
			body, err1 := ioutil.ReadAll(resp.Body)
			if err1 != nil {
				return c.RenderText(err1.Error())
			}
			str := string(body)
			//解析json
			wa := models.ParseWxWebAccessToken(str)
			revel.INFO.Println(str, (*wa).Openid)
			if wa != nil {
				user := models.GetOrCreateWxUser(wa)
				if user != nil {
					c.Session["userid"] = strconv.Itoa(user.UserId)
					c.Session.SetDefaultExpiration()
					revel.INFO.Printf("set cookie wxid %s", c.Session["userid"])
					return c.Redirect("/wxindex")
				} else {
					return c.RenderText("更新用户数据错误")
				}
			} else {
				return c.RenderText("获取access_token 错误")
			}
		}
	}

}

func (c WxApp) getUserbyUserId(uid string) *models.User {
	return models.GetUserByUserId(uid)
}

func (c WxApp) AddUser() revel.Result {
	if user := c.wxId(); user != nil {
		c.RenderArgs["user"] = user
	}
	return nil
}

func (c WxApp) wxId() *models.User {
	if userid, ok := c.Session["userid"]; ok {
		return c.getUserbyUserId(userid)
	}
	return nil
}

func (c WxApp) Index(mode string) revel.Result {
	var user *models.User
	if len(mode) == 0 {
		user = c.wxId()
	} else {
		user = c.getUserbyUserId("1")
		c.Session["userid"] = strconv.Itoa(user.UserId)
		c.Session.SetDefaultExpiration()
	}

	if user != nil {
		revel.INFO.Printf("wellcome back %s", user.Wxopenid)
	} else {
		revel.INFO.Printf("you are the first time to get in, get access_token first")
		return c.Redirect("https://open.weixin.qq.com/connect/oauth2/authorize?appid=wx05054be971d87487&redirect_uri=http%3a%2f%2f117bm.cn%2fwxlogin&response_type=code&scope=snsapi_base&state=123#wechat_redirect")
	}

	//判断是否是召东本人
	if user.Wxopenid != "oJyUL1vz6W-nm41qaihmLMtuKAi4" {
		return c.RenderText("无花果商城稍候开放，请耐心等待～")
	}

	//获取boxlist 商品
	irs, err := c.boxListItems()
	if err != nil {
		revel.ERROR.Println(err)
	}
	return c.Render(user, irs)
}

//在首页列表展示区域的商品  //TODO
func (c WxApp) boxListItems() ([]*models.ItemToRender, error) {
	results, err := models.Dbm.Select(models.Item{}, `select * from item where DisplayPos = ?`, 1)
	if err != err {
		return nil, err
	}
	var irs []*models.ItemToRender
	for _, r := range results {
		i := r.(*models.Item).ItemToRender()
		irs = append(irs, i)
	}
	return irs, nil
}

func (w WxApp) ip() string {
	header := w.Request.Header
	return header.Get("X-Forwarded-For")
}
